package com.yun.algorithmproblem.leetcode;

import com.yun.datastructure.tree.binarytree.domain.TreeNode;


//二叉树最近公共祖先
public class Leetcode236 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null||root.val==p.val||root.val==q.val){
            return root;
        }

        TreeNode left=lowestCommonAncestor(root.left,p,q);
        TreeNode right=lowestCommonAncestor(root.right,p,q);

        if(left!=null&&right!=null){
            return root;
        }

        return left!=null?left:right;
    }


    public static void main(String[] args) {
        TreeNode root = new TreeNode(
                new TreeNode(new TreeNode(4), 2, null),
                1,
                new TreeNode(new TreeNode(5), 3, new TreeNode(6))
        );
        Leetcode236 a = new Leetcode236();
        a.lowestCommonAncestor(root, new TreeNode(3), new TreeNode(4));
    }
}
